import Mock from 'mockjs'
import type { 
  AlarmData, 
  AlarmStats, 
  AlarmSearchParams,
  PaginatedResponse,
  AlarmDistribution,
  AlarmTrend,
  AlarmLevel
} from '../types/alarm'
import { ALARM_TYPES } from '../types/alarm'
import dayjs from 'dayjs'

const Random = Mock.Random

// 生成告警ID
const generateAlarmId = (date: string = dayjs().format('YYYYMMDD')) => {
  return `ALM-${date}-${Random.string('0123456789', 3)}`
}

// 生成IP地址
const generateIp = () => {
  return `192.168.${Random.integer(1, 255)}.${Random.integer(1, 255)}`
}

// 生成域名
const generateDomain = (type: string) => {
  const domains = {
    DGA: () => Random.string('abcdefghijklmnopqrstuvwxyz', 10) + '.com',
    DNS_TUNNEL: () => `tunnel.${Random.domain()}`,
    WEBSHELL: () => `${Random.word()}.${Random.domain()}`,
    BACKDOOR: () => `backdoor.${Random.domain()}`,
    SCAN: () => `scan.${Random.domain()}`,
    EXPLOIT: () => `exploit.${Random.domain()}`,
    MALWARE: () => `malware.${Random.domain()}`,
    BOTNET: () => `botnet.${Random.domain()}`,
    DATA_LEAK: () => `data.${Random.domain()}`,
    BRUTE_FORCE: () => `bruteforce.${Random.domain()}`
  }
  return domains[type as keyof typeof domains]?.() || Random.domain()
}

// 生成描述
const generateDescription = (type: string) => {
  const descriptions = {
    DGA: '检测到可疑的DGA域名访问',
    DNS_TUNNEL: '发现异常的DNS通信模式',
    WEBSHELL: '检测到WebShell特征',
    BACKDOOR: '发现可疑的命令控制通信',
    SCAN: '检测到端口扫描行为',
    EXPLOIT: '检测到漏洞利用尝试',
    MALWARE: '发现恶意软件活动',
    BOTNET: '主机疑似加入僵尸网络',
    DATA_LEAK: '检测到数据外传行为',
    BRUTE_FORCE: '检测到暴力破解尝试'
  }
  return descriptions[type as keyof typeof descriptions] || '未知告警'
}

// 生成单条告警数据
const generateAlarmData = (): AlarmData => {
  const type = Random.pick(Object.values(ALARM_TYPES))
  const level: AlarmLevel = Random.pick(['高危', '中危', '低危'])
  const status = Random.pick(['未处理', '处理中', '已解决'])
  const timestamp = dayjs().subtract(Random.integer(0, 30), 'day').format('YYYY-MM-DD HH:mm:ss')

  return {
    alarmId: generateAlarmId(dayjs(timestamp).format('YYYYMMDD')),
    timestamp,
    level,
    type,
    sourceIp: generateIp(),
    targetDomain: generateDomain(type),
    status,
    description: generateDescription(type)
  }
}

// 生成告警列表数据
const generateAlarmList = (count: number): AlarmData[] => {
  return Array(count).fill(null).map(() => generateAlarmData())
}

// Mock API 响应
Mock.setup({
  timeout: '200-600'
})

// 获取告警列表
Mock.mock(/\/api\/alarms(\?.+)?$/, 'get', (options: any) => {
  const url = new URL(options.url, 'http://dummy.com')
  const params: AlarmSearchParams = {
    page: parseInt(url.searchParams.get('page') || '1'),
    pageSize: parseInt(url.searchParams.get('pageSize') || '10'),
    level: url.searchParams.get('level') as AlarmLevel || undefined,
    status: url.searchParams.get('status') as any,
    type: url.searchParams.get('type') as any,
    keyword: url.searchParams.get('keyword')
  }

  let data = generateAlarmList(100)

  // 应用过滤
  if (params.level) {
    data = data.filter(item => item.level === params.level)
  }
  if (params.status) {
    data = data.filter(item => item.status === params.status)
  }
  if (params.type) {
    data = data.filter(item => item.type === params.type)
  }
  if (params.keyword) {
    const keyword = params.keyword.toLowerCase()
    data = data.filter(item =>
      item.alarmId.toLowerCase().includes(keyword) ||
      item.sourceIp.toLowerCase().includes(keyword) ||
      item.targetDomain.toLowerCase().includes(keyword) ||
      item.description.toLowerCase().includes(keyword)
    )
  }

  // 分页
  const start = (params.page! - 1) * params.pageSize!
  const items = data.slice(start, start + params.pageSize!)

  return {
    code: 200,
    message: 'success',
    data: {
      total: data.length,
      items
    } as PaginatedResponse<AlarmData>
  }
})

// 获取告警统计
Mock.mock('/api/alarms/stats', 'get', () => {
  const stats: AlarmStats = {
    unprocessed: Random.integer(50, 200),
    processing: Random.integer(30, 100),
    resolved: Random.integer(1000, 2000),
    total: 0
  }
  stats.total = stats.unprocessed + stats.processing + stats.resolved

  return {
    code: 200,
    message: 'success',
    data: stats
  }
})

// 获取告警分布
Mock.mock('/api/alarms/distribution', 'get', () => {
  const distribution: Record<string, AlarmDistribution[]> = {
    day: [
      { name: '高危告警', value: Random.integer(20, 50) },
      { name: '中危告警', value: Random.integer(40, 80) },
      { name: '低危告警', value: Random.integer(10, 30) }
    ],
    week: [
      { name: '高危告警', value: Random.integer(100, 200) },
      { name: '中危告警', value: Random.integer(200, 300) },
      { name: '低危告警', value: Random.integer(50, 100) }
    ],
    month: [
      { name: '高危告警', value: Random.integer(400, 600) },
      { name: '中危告警', value: Random.integer(700, 900) },
      { name: '低危告警', value: Random.integer(200, 300) }
    ]
  }

  return {
    code: 200,
    message: 'success',
    data: distribution
  }
})

// 获取告警趋势
Mock.mock('/api/alarms/trend', 'get', () => {
  const dates = Array(7).fill(null).map((_, index) => {
    return dayjs().subtract(6 - index, 'day').format('MM-DD')
  })

  const trend: AlarmTrend = {
    dates,
    all: dates.map(() => Random.integer(100, 200)),
    high: dates.map(() => Random.integer(30, 70)),
    medium: dates.map(() => Random.integer(50, 100)),
    low: dates.map(() => Random.integer(10, 30))
  }

  return {
    code: 200,
    message: 'success',
    data: trend
  }
}) 